package com.ruoyi.system.service.impl;

import java.util.List;

import com.ruoyi.system.domain.RoomInfo;
import com.ruoyi.system.mapper.RoomInfoMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;
import com.ruoyi.system.mapper.BedInfoMapper;
import com.ruoyi.system.domain.BedInfo;
import com.ruoyi.system.service.IBedInfoService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 床位信息Service业务层处理
 */
@Service
public class BedInfoServiceImpl implements IBedInfoService {
    @Autowired
    private BedInfoMapper bedInfoMapper;

    @Autowired
    private RoomInfoMapper roomInfoMapper;

    /**
     * 查询床位信息
     * 
     * @param id 床位ID
     * @return 床位信息
     */
    @Override
    public BedInfo selectBedInfoById(Long id) {
        return bedInfoMapper.selectBedInfoById(id);
    }

    /**
     * 查询床位信息列表
     * 
     * @param bedInfo 床位信息
     * @return 床位信息
     */
    @Override
    public List<BedInfo> selectBedInfoList(BedInfo bedInfo) {
        return bedInfoMapper.selectBedInfoList(bedInfo);
    }

    /**
     * 新增床位信息
     * 
     * @param bedInfo 床位信息
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = {Exception.class, DuplicateKeyException.class})
    public int insertBedInfo(BedInfo bedInfo) {
        // 生成床位编码
        String maxCode = bedInfoMapper.getMaxBedCode();
        String newCode;
        if (maxCode == null) {
            newCode = "BD0001";
        } else {
            int num = Integer.parseInt(maxCode.substring(2)) + 1;
            newCode = String.format("BD%04d", num);
        }
        bedInfo.setBedCode(newCode);
        Long roomId = bedInfo.getRoomId();
        RoomInfo roomInfo = roomInfoMapper.selectRoomInfoById(roomId);
        bedInfo.setBuildingId(roomInfo.getBuildingId());
        return bedInfoMapper.insertBedInfo(bedInfo);
    }

    /**
     * 修改床位信息
     * 
     * @param bedInfo 床位信息
     * @return 结果
     */
    @Override
    public int updateBedInfo(BedInfo bedInfo) {
        Long roomId = bedInfo.getRoomId();
        RoomInfo roomInfo = roomInfoMapper.selectRoomInfoById(roomId);
        bedInfo.setBuildingId(roomInfo.getBuildingId());
        return bedInfoMapper.updateBedInfo(bedInfo);
    }

    /**
     * 批量删除床位信息
     * 
     * @param ids 需要删除的床位ID
     * @return 结果
     */
    @Override
    public int deleteBedInfoByIds(Long[] ids) {
        return bedInfoMapper.deleteBedInfoByIds(ids);
    }

    /**
     * 删除床位信息信息
     * 
     * @param id 床位ID
     * @return 结果
     */
    @Override
    public int deleteBedInfoById(Long id) {
        return bedInfoMapper.deleteBedInfoById(id);
    }
} 